package com.example.kotlindemo620

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_navigation)
        bottomNav.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_home -> replaceFragment(HomeFragment())
                R.id.nav_request1 -> {
                    replaceFragment(Request1Fragment())
                    makeHttpRequest("https://e.weather.com.cn/news/duanshipin.shtml")
                }
                R.id.nav_request2 -> {
                    replaceFragment(Request2Fragment())
                    makeHttpRequest("https://github.com/")
                }
                R.id.nav_tail -> replaceFragment(TailFragment())
            }
            true
        }
        bottomNav.selectedItemId = R.id.nav_home // 默认选中首页
    }

    private fun replaceFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }

    private fun makeHttpRequest(url: String) {
        Thread {
            try {
                val client = okhttp3.OkHttpClient()
                val request = okhttp3.Request.Builder().url(url).build()
                client.newCall(request).execute().use { response ->
                    // 可根据需要处理响应
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }.start()
    }
}